import {
  getStore,
  setStore
} from '../../util/store'
import {
  isURL,
  validatenull
} from '../../util/validate'
import {
  getUserInfo,
  loginByMobile,
  loginBySocial,
  loginByUsername,
  loginSuperUser,
  logout,
  refreshToken,
  licenseActivate,
  checkActivate
} from '../../api/login'
import {
  deepClone,
  encryption
} from '../../util/util'
import webiste from '../../const/website'
import {
  GetMenu,
  getMenuAndMoudle
} from '../../api/admin/menu'

function addPath(ele, first) {
  const menu = webiste.menu
  const propsConfig = menu.props
  const propsDefault = {
    label: propsConfig.label || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon]
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0
  if (!isChild) ele[propsDefault.children] = []
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach(child => {
      addPath(child)
    })
  }
}

const user = {
  state: {
    license: '',
    userInfo: {},
    orgInfo: {},
    deptInfo: {},
    permissions: {},
    roles: [],
    menu: getStore({
      name: 'menu'
    }) || [],
    module: getStore({
      name: 'module'
    }) || [],
    menuAll: [],
    expires_in: getStore({
      name: 'expires_in'
    }) || '',
    access_token: getStore({
      name: 'access_token'
    }) || '',
    refresh_token: getStore({
      name: 'refresh_token'
    }) || '',
    currentModule: getStore({
      name: 'currentModule'
    }) || ''
  },
  actions: {
    // 根据用户名登录
    LoginByUsername({
      commit
    }, userInfo) {
      const user = encryption({
        data: userInfo,
        key: 'sonesonesonesone',
        param: ['password']
      })
      return new Promise((resolve, reject) => {
        loginByUsername(user.username, user.password, user.code, user.randomStr).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 超级管理员登录
    loginSuperUser({
      commit
    }, userInfo) {
      const user = encryption({
        data: userInfo,
        key: 'sonesonesonesone',
        param: ['password']
      })
      return new Promise((resolve, reject) => {
        loginSuperUser(user.username, user.password, user.code, user.randomStr).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据手机号登录
    LoginByPhone({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByMobile(userInfo.mobile, userInfo.code).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据OpenId登录
    LoginBySocial({
      commit
    }, param) {
      return new Promise((resolve, reject) => {
        loginBySocial(param.state, param.code).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetUserInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          const data = res.data.data || {}
          commit('SET_USERIFNO', data.sysUser)
          commit('SET_ORGIFNO', data.orgInfo)
          commit('SET_DEPTIFNO', data.deptInfo)
          commit('SET_ROLES', data.roles || [])
          commit('SET_PERMISSIONS', data.permissions || [])
          commit('SET_LICENSE', '')
          resolve(data)
        }).catch((res) => {
          /* 许可证过期唯一标识：license_invalid（License expired ），跳转激活页面
       许可证锁定唯一标识：license_locked（License locked），跳转登录页面  */
          // 判断许可证是否激活/过期/锁定
          if (String(res).indexOf('License locked') > -1) {
            commit('SET_LICENSE', 'locked')
          } else if (String(res).indexOf('License expired') > -1) {
            commit('SET_LICENSE', 'expired')
          } else {
            commit('SET_LICENSE', '')
          }
          reject(res)
        })
      })
    },
    // 刷新token
    RefreshToken({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.refresh_token).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({
      commit
    }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_MENU', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_USERIFNO', {})
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_EXPIRES_IN', '')
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 注销session
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_MENU', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_USERIFNO', {})
        commit('SET_ACCESS_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG')
        commit('CLEAR_LOCK')
        resolve()
      })
    },
    // 获取系统菜单
    GetMenu({
      commit
    }, idx) {
      return new Promise(resolve => {
        GetMenu(idx).then((res) => {
          const data = res.data.data
          const menu = deepClone(data)
          // menu.forEach(ele => {
          //   addPath(ele)
          // })
          // commit('SET_MENU', menu)
          resolve(menu)
        })
      })
    },
    // 设置菜单
    SetMenu({
      commit
    }, menu) {
      menu.forEach(ele => {
        addPath(ele)
      })
      commit('SET_MENU', menu)
    },
    // 获取模块
    GetModule({
      commit
    }) {
      return new Promise(resolve => {
        getMenuAndMoudle().then(res => {
          const list = deepClone(res.data.data)
          commit('SET_MODULE', list.map(res => {
            delete res.menuTreeList
            return res
          }))
          resolve(res.data.data)
        })
      })
    },
    // 设置当前module
    SetModule({
      commit
    }, currentModule) {
      commit('SET_CURRENT_MODULE', currentModule)
    },
    // 许可证激活
    LicenseActivate({
      commit
    }, licenseKey) {
      return new Promise((resolve, reject) => {
        licenseActivate(licenseKey).then((res) => {
          resolve(res)
        }).catch((res) => {
          reject(res)
        })
      })
    },
    // 许可证激活
    CheckActivate({
                      commit
                    },licenseKey) {
      return new Promise((resolve, reject) => {
        checkActivate(licenseKey).then((res) => {
          resolve(res)
        }).catch((res) => {
          reject(res)
        })
      })
    },
  },
  mutations: {
    SET_ACCESS_TOKEN: (state, access_token) => {
      state.access_token = access_token
      setStore({
        name: 'access_token',
        content: state.access_token,
        type: 'session'
      })
    },
    SET_EXPIRES_IN: (state, expires_in) => {
      state.expires_in = expires_in
      setStore({
        name: 'expires_in',
        content: state.expires_in,
        type: 'session'
      })
    },
    SET_REFRESH_TOKEN: (state, rfToken) => {
      state.refresh_token = rfToken
      setStore({
        name: 'refresh_token',
        content: state.refresh_token,
        type: 'session'
      })
    },
    SET_LICENSE: (state, license) => {
      state.license = license
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_ORGIFNO: (state, orgInfo) => {
      state.orgInfo = orgInfo
    },
    SET_DEPTIFNO: (state, deptInfo) => {
      state.deptInfo = deptInfo
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({
        name: 'menu',
        content: state.menu,
        type: 'session'
      })
    },
    SET_MODULE: (state, module) => {
      state.module = module
      setStore({
        name: 'module',
        content: state.module,
        type: 'session'
      })
    },
    SET_CURRENT_MODULE: (state, currentModule) => {
      state.currentModule = currentModule
      setStore({
        name: 'currentModule',
        content: state.currentModule,
        type: 'session'
      })
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      const list = {}
      for (let i = 0; i < permissions.length; i++) {
        list[permissions[i]] = true
      }
      state.permissions = list
    }
  }

}
export default user
